#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QStyle>
#include <QLabel>
#include <QMessageBox>
#include <QDebug>
#include <QMouseEvent>
#include <QApplication>
#define WINDOWS_TITLE_STRING "相机控制及图像采集软件"
#define SOFT_VERSION "V0.1.0"
/**
 * @brief 主窗口构造函数，初始化UI及日志组件
 * @param parent 父窗口指针（用于窗口层级管理）
 */
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_bPressed(false)
{
    ui->setupUi(this);
    //隐藏系统的标题栏
    setWindowFlags(Qt::FramelessWindowHint);
    setContentsMargins(1, 1, 1, 1);
    //设置标题
    setWindowTitle(WINDOWS_TITLE_STRING SOFT_VERSION);
    ui->label_Title->setText(WINDOWS_TITLE_STRING SOFT_VERSION);

    // 连接标题栏按钮的信号与槽
    connect(ui->toolButton_Mini, &QToolButton::clicked, this, &MainWindow::onToolButtonMiniClicked);
    connect(ui->toolButton_Max, &QToolButton::clicked, this, &MainWindow::onToolButtonMaxClicked);
    connect(ui->toolButton_Close, &QToolButton::clicked, this, &MainWindow::onToolButtonCloseClicked);

    // 连接窗口状态变化信号
    m_pDockWidgetManager=new DockWidgetManager();
    ui->gridLayout_WorkSpace->addWidget(m_pDockWidgetManager);

    // 默认插件目录为程序同级plugins文件夹
    QString pluginsDir = QCoreApplication::applicationDirPath() + "/plugins";
    m_pPluginManager=new PluginManager(this);
    // 关联插件的信号
    connect(m_pPluginManager, &PluginManager::pluginLoaded, this, [this](CameraPluginInterface *cameraPlugin)
    {
        if (cameraPlugin)
        {
            // 连接插件信号到DockWidgetManager的方法
            connect(cameraPlugin, &CameraPluginInterface::registerWidgetToDock, m_pDockWidgetManager, &DockWidgetManager::registerWidgetToDock);
            connect(cameraPlugin, &CameraPluginInterface::registerGraphicsDisplayWidget, m_pDockWidgetManager, &DockWidgetManager::registerGraphicsDisplayWidget);
            // 分别连接registerMenuItem的三个重载版本
            connect(cameraPlugin, QOverload<int, QObject*>::of(&CameraPluginInterface::registerMenuItem), 
                    m_pDockWidgetManager, QOverload<int, QObject*>::of(&DockWidgetManager::onRegisterMenuItem));
            connect(cameraPlugin, QOverload<const QVector<int>&, const QString&, QDialog*>::of(&CameraPluginInterface::registerMenuItem), 
                    m_pDockWidgetManager, QOverload<const QVector<int>&, const QString&, QDialog*>::of(&DockWidgetManager::onRegisterMenuItem));
            connect(cameraPlugin, QOverload<int, const QString&>::of(&CameraPluginInterface::registerMenuItem),
                    m_pDockWidgetManager, QOverload<int, const QString&>::of(&DockWidgetManager::onRegisterMenuItem));
//            connect(cameraPlugin,SIGNAL(registerMenuItem(int menuIndex, const QString &title)),
//                    m_pDockWidgetManager, SLOT(onRegisterMenuItem(int menuIndex, const QString &title)));
            connect(cameraPlugin, &CameraPluginInterface::unregisterGraphicsDisplayWidget, m_pDockWidgetManager, &DockWidgetManager::unregisterGraphicsDisplayWidget);
            connect(cameraPlugin, &CameraPluginInterface::switchToGraphicsDisplayWidget, m_pDockWidgetManager, &DockWidgetManager::switchToGraphicsDisplayWidget);

            // 连接DockWidgetManager的信号到插件
            connect(m_pDockWidgetManager, &DockWidgetManager::graphicsDisplayWidgetSwitched, cameraPlugin, &CameraPluginInterface::switchToGraphicsDisplayWidget);
            connect(m_pDockWidgetManager, &DockWidgetManager::graphicsDisplayWidgetClosed, cameraPlugin, &CameraPluginInterface::closeGraphicsDisplayWidget);
        }
    });
    m_pPluginManager->loadPlugins(pluginsDir);

}

MainWindow::~MainWindow()
{
    // 删除插件管理器，确保所有插件都能正确析构
    delete m_pPluginManager;
    m_pPluginManager = nullptr;

    // 最后删除UI组件
    delete ui;
}
/**
 * @brief 初始化Dock标题使用自定义的标题代替
 * 注意：此方法已移至DockWidgetManager类中实现
 */

/**
 * @brief 实现注册widget到指定QDockWidget的功能
 * @param type 要注册到的QDockWidget类型
 * @param widget 要注册的widget指针
 * @return 注册成功返回true，失败返回false
 * @details 该方法根据传入的枚举类型找到对应的QDockWidget，
 *          移除现有的widget（如果有），然后设置新的widget
 */
bool MainWindow::registerWidgetToDock(DockWidgetType type, QWidget *widget)
{
    // 委托给DockWidgetManager处理
    return m_pDockWidgetManager->registerWidgetToDock(type, widget);
}
/**
 * @brief 注册widget到图形显示区域
 * @param graphicsGuid 图形的Guid
 * @param titleString 标题名称
 * @param pWidget 要注册的widget指针
 */
void MainWindow::registerGraphicsDisplayWidget(const QString &graphicsGuid, const QString &titleString, QWidget *pWidget)
{
    // 委托给DockWidgetManager处理
    m_pDockWidgetManager->registerGraphicsDisplayWidget(graphicsGuid, titleString, pWidget);
}

/**
 * @brief 注销图形显示窗口
 * @param graphicsGuid 要注销的图形GUID
 */
void MainWindow::unregisterGraphicsDisplayWidget(const QString &graphicsGuid)
{
    // 委托给DockWidgetManager处理
    m_pDockWidgetManager->unregisterGraphicsDisplayWidget(graphicsGuid);
}

/**
 * @brief 切换到指定的图形显示窗口
 * @param graphicsGuid 要切换到的图形GUID
 */
void MainWindow::switchToGraphicsDisplayWidget(const QString &graphicsGuid)
{
    // 委托给DockWidgetManager处理
    m_pDockWidgetManager->switchToGraphicsDisplayWidget(graphicsGuid);
}

/**
 * @brief 实现注册菜单项或菜单到主窗口的功能
 * @param menuIndex 菜单索引，表示菜单项的位置。如果为-1，则添加为新菜单
 * @param menuObject 菜单对象指针，可以是QAction或QMenu
 * @details 该方法将接收到的菜单对象添加到主窗口的菜单栏中
 */
void MainWindow::registerMenuItem(int menuIndex, QObject *menuObject)
{
    // 委托给DockWidgetManager处理
    m_pDockWidgetManager->onRegisterMenuItem(menuIndex, menuObject);
}

/**
 * @brief 最小化窗口槽函数
 */
void MainWindow::onToolButtonMiniClicked()
{
    this->showMinimized();
}

/**
 * @brief 最大化/还原窗口槽函数
 */
void MainWindow::onToolButtonMaxClicked()
{
    if (this->isMaximized())
    {
        this->showNormal();
        onWindowStateChanged(Qt::WindowMaximized,Qt::WindowNoState);
    }
    else
    {
        this->showMaximized();
        onWindowStateChanged(Qt::WindowNoState,Qt::WindowMaximized);
    }
}

/**
 * @brief 关闭窗口槽函数
 */
void MainWindow::onToolButtonCloseClicked()
{
    this->close();
}

/**
 * @brief 窗口状态变化槽函数
 * @param oldState 旧的窗口状态
 * @param newState 新的窗口状态
 */
void MainWindow::onWindowStateChanged(Qt::WindowStates oldState, Qt::WindowStates newState)
{
    Q_UNUSED(oldState)

    // 根据窗口状态修改按钮的objectName
    if (newState == Qt::WindowMaximized)
    {
        // 窗口最大化时，将按钮重命名为toolButton_Recover
        ui->toolButton_Max->setObjectName("toolButton_Recover");
    }
    else
    {
        // 窗口非最大化时，将按钮重命名为toolButton_Max
        ui->toolButton_Max->setObjectName("toolButton_Max");
    }

    // 更新按钮的样式
    ui->toolButton_Max->style()->unpolish(ui->toolButton_Max);
    ui->toolButton_Max->style()->polish(ui->toolButton_Max);
    ui->toolButton_Max->update();
}

/**
 * @brief 鼠标按下事件处理
 */
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && event->y() <= 40) // 只在标题栏区域响应拖动
    {
        m_bPressed = true;
        m_pointMove = event->globalPos() - this->frameGeometry().topLeft();
        event->accept();
    }
}

/**
 * @brief 鼠标移动事件处理
 */
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (m_bPressed && (event->buttons() & Qt::LeftButton))
    {
        move(event->globalPos() - m_pointMove);
        event->accept();
    }
}

/**
 * @brief 鼠标释放事件处理
 */
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        m_bPressed = false;
        event->accept();
    }
}

